#include "stdafx.h"
#include "CP2P.h"
#include <iostream>
using namespace std;
#pragma comment(lib,"ws2_32.lib")



bool InitSockeT()
{
	WORD wVersionRequested;
	WSADATA wsaData;
	int err;
	wVersionRequested = MAKEWORD(1,1);
	err = WSAStartup( wVersionRequested, &wsaData );
	if (err != 0)
	{
		return false;
	}

	return true;
}

bool CreateListenSocket()
{
	int iRet=0;
	SOCKADDR_IN addrSrv;

	addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
	addrSrv.sin_family=AF_INET;
	addrSrv.sin_port=htons(6666);
	sck_server=socket(AF_INET, SOCK_DGRAM,0);
	iRet=bind(sck_server,(SOCKADDR *)&addrSrv,sizeof(SOCKADDR_IN));
	if (iRet!=0)
	{
		return false;
	}
	CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)SocketThread,(LPVOID)&sck_server,NULL,NULL);
	return true;
}

DWORD SocketThread(LPVOID param)
{
	SOCKET *scktemp=(SOCKET*)param;
	BYTE buffer[1024];
	int ilen;
	SOCKADDR_IN sck_addr_in;
	int i,j;
	int iRet=0;
	int iSizeSck_Addr=sizeof(SOCKADDR);
	Client_Tag sck_clt_temp;
	while(1)
	{
		ZeroMemory(&sck_clt_temp,sizeof(sck_clt_temp));
		iRet=recvfrom(*scktemp,(char*)buffer,1024,0,(SOCKADDR *)&sck_addr_in,&iSizeSck_Addr);
		for (i=0;i<vec_sck_client.size() && iRet > 0 ;i++)
		{
			if (vec_sck_client[i].sck_addr_port.sin_addr.S_un.S_addr==sck_addr_in.sin_addr.S_un.S_addr)
			{
				if (vec_sck_client[i].bIsLen == false)
				{
					sck_clt_temp.usRecvLen=*(USHORT*)buffer;
				}
				break;
			}
		}
		sck_clt_temp.sck_addr_port=sck_addr_in;
		if (iRet>0 && sck_clt_temp.bIsLen == false)
		{
			vec_sck_client.push_back(sck_clt_temp);
		}
	}

	return 0;

}
